﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using dnAnalytics.Math;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The inverse Gamma distribution is a distribution over the positive real numbers parameterized by
    /// two positive parameters.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class InverseGamma : IContinuousDistribution
    {
        // Inverse Gamma parameter a.
        private readonly double mA;

        // Inverse Gamma parameter b.
        private readonly double mB;

        /// <summary>
        /// Constructs an inverse Gamma distribution.
        /// </summary>
        /// <param name="a">The first parameter of the inverse Gamma distribution.</param>
        /// <param name="b">The second parameter of the inverse Gamma distribution.</param>
        public InverseGamma(double a, double b)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(a, b);
            }

            mA = a;
            mB = b;
            RandomNumberGenerator = new System.Random();
        }

        /// <summary>
        /// The shape parameter.
        /// </summary>
        public double A
        {
            get { return mA; }
        }

        /// <summary>
        /// The scale parameter.
        /// </summary>
        public double B
        {
            get { return mB; }
        }

        /// <summary>
        /// A string representation of the distribution.
        /// </summary>
        public override string ToString()
        {
            return "InverseGamma(Shape = " + mA + ", Inverse Scale = " + mB + ")";
        }

        #region IDistribution Members

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        /// <value></value>
        public double Mean
        {
            get { return mB/(mA - 1.0); }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        /// <value></value>
        public double StdDev
        {
            get { return mB/((mA - 1.0)*System.Math.Sqrt(mA - 2.0)); }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        /// <value></value>
        public double Variance
        {
            get { return mB*mB/((mA - 1.0)*(mA - 1.0)*(mA - 2.0)); }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get { return mA + System.Math.Log(mB) + Math.SpecialFunctions.GammaLn(mA) - (1 + mA)*Math.SpecialFunctions.DiGamma(mA); }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IContinuousDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public double Mode
        {
            get { return mB/(mA + 1.0); }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public double Median
        {
            get { throw new NotImplementedException(); }
        }

        /// <summary>
        /// Computes values of the probability density function.
        /// </summary>
        /// <param name="x">The location in the domain where we want to evaluate the probability density function.</param>
        /// <returns></returns>
        public double Density(double x)
        {
            if (x >= 0.0)
            {
                return System.Math.Pow(mB, mA)*System.Math.Pow(x, -mA - 1.0)*System.Math.Exp(-mB/x)/Math.SpecialFunctions.Gamma(mA);
            }

            return 0.0;
        }

        /// <summary>
        /// Samples an Inverse Gamma distributed random variable.
        /// </summary>
        public double Sample()
        {
            return DoSample(RandomNumberGenerator, mA, mB);
        }

        /// <summary>
        /// Samples an array of inverse Gamma distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public double[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mA, mB);
        }

        #endregion

        /// <summary>
        /// Evaluates the cumulative distribution function for the Gamma distribution.
        /// </summary>
        public double CumulativeDistribution(double x)
        {
            return SpecialFunctions.IncompleteGamma(mA, mB / x, false);
        }

        /// <summary>
        /// Evaluates the logarithm of the probability density function.
        /// </summary>
        public double DensityLn(double x)
        {
            return mA * System.Math.Log(mB) - (mA + 1.0) * System.Math.Log(x) - mB / x - SpecialFunctions.GammaLn(mA);
        }

        /// <summary>
        /// Samples an InverseGamma distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="a">The first parameter of the Gamma distribution.</param>
        /// <param name="b">The second parameter of the Gamma distribution.</param>
        public static double Sample(System.Random rnd, double a, double b)
        {
            return 1.0/Gamma.Sample(rnd, a, b);
        }

        /// <summary>
        /// Samples an array of InverseGamma distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="a">The first parameter of the InverseGamma distribution.</param>
        /// <param name="b">The second parameter of the InverseGamma distribution.</param>
        public static double[] Sample(System.Random rnd, int n, double a, double b)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(a, b);
            }

            return DoSample(rnd, n, a, b);
        }

        /// <summary>
        /// Check the parameters of the inverse Gamma distribution.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">If any of the inverse Gamma parameters are non-positive.</exception>
        private static void CheckParameters(double a, double b)
        {
            if (a <= 0.0)
            {
                throw new ArgumentOutOfRangeException("a", Properties.Resources.NotPositive);
            }
            if (b <= 0.0)
            {
                throw new ArgumentOutOfRangeException("b", Properties.Resources.NotPositive);
            }
        }

        private static double DoSample(System.Random rnd, double a, double b)
        {
            return 1.0/Gamma.Sample(rnd, a, b);
        }

        private static double[] DoSample(System.Random rnd, int n, double a, double b)
        {
            double[] arr = new double[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = DoSample(rnd, a, b);
            }
            return arr;
        }
    }
}